package com.leo.foodmaster.commons.config.security;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import com.leo.foodmaster.commons.constants.AuthConstants;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 自定MetadataSource
 * </p>
 *
 * @author ：Leo
 * @since ：2021-07-03 13:59
 */
@Component
public class CustomSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private PermitAllUrlProperties permitAllUrlProperties;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
        String requestUri = request.getRequestURI();
        PathMatcher pathMatcher = new AntPathMatcher();

        // 六、验证权限
        Set<String> authorities = new HashSet<>();

        // 1.从白名单中取出白名单接口
        String[] ignoreUrls = permitAllUrlProperties.getIgnoreUrls();
        for (String ignoreUrl : ignoreUrls) {
            if (pathMatcher.match(ignoreUrl, requestUri)) {
                return SecurityConfig.createList(ArrayUtil.toArray(authorities, String.class));
            }
        }


        // 2.从缓存中获取资源权限角色关系列表
        Map<Object, Object> permissionRoles = redisTemplate.opsForHash().entries(AuthConstants.PERMISSION_ROLES_KEY);
        // 3.请求路径匹配到的资源需要的角色权限集合authorities统计
        String restPath = request.getMethod() + "_" + requestUri;
        for (Object o : permissionRoles.keySet()) {
            String permStr = (String) o;
            if (pathMatcher.match(permStr, restPath)) {
                authorities.addAll(Convert.toList(String.class, permissionRoles.get(permStr)));
            }
        }

        if (authorities.isEmpty()) {
            authorities.add("ROLE_ANONYMOUS");
        }
        return SecurityConfig.createList(ArrayUtil.toArray(authorities, String.class));
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return new ArrayList<>();
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
